package csc.daonjpa.java.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import csc.daonjpa.java.domain.Account;


/**
 * DAO class for Account entity. This class contains all methods that inserts/updates/deletes
 * account info
 * @author nvu3
 *
 */
@Component
public class AccountDAO {
	
	 @PersistenceContext
	  private EntityManager em;
	/**
	 * @return all accounts from Account table
	 */
	 @Transactional
	public List<Account> getAccounts() {
//		EntityManager em = TransactionManager.getEntityManager();
		TypedQuery<Account> query = em.createQuery("SELECT a FROM Account a", Account.class);
		List<Account> accounts = null;
		accounts = query.getResultList();
		return accounts;
	}
	/**
	 * Add account to Account table
	 * @param account Account entity that contains mapped with each column in Account table
	 * @return
	 */
	@Transactional
	public boolean addAccount(Account account) {
//		EntityManager em = TransactionManager.getEntityManager();
		em.persist(account);
		return true;
	}
	/**
	 * 
	 * @param id
	 * @return account by primary key.
	 */
	@Transactional
	public Account getAccount(Long id) {
//		EntityManager em = TransactionManager.getEntityManager();
		Account account = em.find(Account.class, id);
		return account;
	}
	/**
	 * 
	 * @param loginId
	 * @return all accounts of the user logged in
	 */
	@Transactional
	public List<Account> getAccountByCustomer(String loginId) {
//		EntityManager em = TransactionManager.getEntityManager();
		TypedQuery<Account> query = em.createQuery("SELECT c FROM Account c WHERE c.customer.loginId = :loginId", Account.class);
		query.setParameter("loginId", loginId);
		List<Account> accounts = null;
		accounts = query.getResultList();
		return accounts;
	}
}
